#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#define mod 1000000007
#define ll long long
#define inf (1LL<<60)
using namespace std;
ll read()
{
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
ll ans;
int a,b;
void exgcd(int a,int b,int &x,int &y)
{
	if(b==0){x=1;y=0;return;}
	exgcd(b,a%b,x,y);
	int t=x;x=y,y=t-a/b*y;
}
int main()
{
	a=read();b=read();
	int x,y;
	exgcd(a,b,x,y);
	x=(x%b+b)%b;
	cout<<x<<endl;
	return 0;
}
